package com.security.tool;

import io.jsonwebtoken.CompressionCodec;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @ClassName TokenManager
 * @Description token操作工具类
 * @Author liuzhihui
 * @Date 17/3/2021 下午 10:19
 * @Version 1.0
 **/
@Component
public class TokenManager {
    //token有效期
    private long tokenExpiration = 24*60*60*1000;
    //编码密钥
    private String tokenSignKey = "123456";

    //根据用户名生成token
    public String createToken(String username){
        String token = Jwts.builder().setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis()+tokenExpiration))
                .signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
        return token;
    }
    //根据token获取用户信息
    public String getUserInfoFromToken(String token){
        return Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
    }

    public void removeToken(String token){
        //jwt token无需删除，客户端扔掉即可
    }
}
